#include "networkmanager.h"

NetWorkManager* NetWorkManager::m_Instance = nullptr;
QMutex NetWorkManager::m_mutex;

NetWorkManager *NetWorkManager::getInstance(QObject *parent)
{
    // 双重检查锁定，保证线程安全且高效
    if (!m_Instance) {
        QMutexLocker locker(&m_mutex); // 自动加锁/解锁，避免死锁
        if (!m_Instance) {
            m_Instance = new NetWorkManager(parent);
        }
    }
    return m_Instance;
}

void NetWorkManager::processCudata_ChangFeng(const QJsonObject &originalData)
{
    QMap<QString, cutData> dataMap;

    // 直接解析根层级的 bar 数组（原数据无 "data" 字段）
    const QJsonArray barArray = originalData["bar"].toArray();

    for (const QJsonValue &barValue : barArray) {
        QJsonObject bar = barValue.toObject();
        QString barType = bar["barName"].toString();
        double barLength = bar["length"].toDouble();  // 直接获取数值
        QString barColor = bar["barColor"].toString();

        // 遍历型材中的部件 (piece)
        const QJsonArray pieceArray = bar["piece"].toArray();
        for (const QJsonValue &pieceValue : pieceArray) {
            QJsonObject piece = pieceValue.toObject();
            QJsonObject cutObj = piece["cut"].toObject();

            // 构建 cutData 实例
            cutData current {
                piece["ordercode"].toString(),       // 订单编号
                barType,                          // 型材类型
                piece["buyer"].toString(),         // 产品名称
                barColor,                         // 颜色
                cutObj["length"].toString().toDouble(), // 切割长度
                piece["num"].toInt(),            // 切割数量
                barLength,                        // 原料长度
                cutObj["sxB"].toString().toDouble(),    // 左侧角度
                cutObj["dxB"].toString().toDouble(),     // 右侧角度
                0
            };

            QString uniqueKey = QString("%1|%2|%3|%4|%5|%6|%7|%8").arg(current.orderCode,
                                                                       current.profileType,
                                                                       current.productName,
                                                                       current.color,
                                                                       QString::number(current.cutLength),
                                                                       QString::number(current.materialLength),
                                                                       QString::number(current.leftAngle),
                                                                       QString::number(current.rightAngle));

            // 统计数量：若已存在相同组合则累加，否则添加新记录
            if (dataMap.contains(uniqueKey)) {
                dataMap[uniqueKey].cutCount++;
            } else {
                dataMap[uniqueKey] = current;
            }
        }
    }

    // 转换为数组式存储
    aggregatedData = dataMap.values().toVector();

    // qDebug()<<"当前 Model DataList 总数: "<<model->count();
    // model->setDataList(aggregatedData);

    emit send_UpData_ListView_Signal(aggregatedData);
    // 数组式访问示例
    for (int i = 0; i < aggregatedData.size(); ++i) {
        const auto &data = aggregatedData[i];
        // // model->addData(aggregatedData[i]);
        qDebug() << "记录" << i + 1 << " : "<<"订单号:"<<data.orderCode<<"类型:"<<data.profileType<<"名称: "<<data.productName<<"颜色: "<<data.color<<"切割长度: "<<data.cutLength<<"左角度: "<<data.leftAngle<<"右角度: "<<data.rightAngle<<"切割数量: "<<data.cutCount<<"原料长度: "<<data.materialLength;
    }

    qDebug()<<"长风 - 解析完成 : 共有 "<<aggregatedData.size()<<" 条数据";

    aggregatedData.clear();
}

void NetWorkManager::processCudata_XinGeEr(const QJsonObject &originalData)
{
    QJsonArray barArray = originalData["Bar"].toArray();
    QMap<QString, cutData> dataMap;  // 用于统计相同组合的数量

    // 遍历Bar数组
    foreach (const QJsonValue& barValue, barArray) {
        if (!barValue.isObject()) continue;
        QJsonObject barObj = barValue.toObject();

        cutData data;
        // 1. 提取订单号 (field3格式: "1,订单号,XXX")
        if (barObj.contains("field3") && barObj["field3"].isString()) {
            data.orderCode = extractValue(barObj["field3"].toString());
        }

        // 2. 提取型材类型 (假设field4格式: "3,型材类型,XXX")
        if (barObj.contains("ProfileCode") && barObj["ProfileCode"].isString()) {
            data.profileType = extractValue(barObj["ProfileCode"].toString());
        }

        // 3. 提取产品名称 (假设field5格式: "4,产品名称,XXX")
        if (barObj.contains("ProfileName") && barObj["ProfileName"].isString()) {
            data.productName = extractValue(barObj["ProfileName"].toString());
        }

        // 4. 提取颜色 (假设field10格式: "10,颜色,XXX")
        if (barObj.contains("field10") && barObj["field10"].isString()) {
            data.color = extractValue(barObj["field10"].toString());
        }
        // 补充：如果颜色也存在于MaterielColor字段，可做兼容处理
        else if (barObj.contains("MaterielColor") && barObj["MaterielColor"].isString()) {
            data.color = barObj["MaterielColor"].toString().trimmed();
        }

        // 5. 提取切割长度 (假设field2格式: "2,加工长度,XXX")
        if (barObj.contains("CutLength") && barObj["CutLength"].isString()) {
            QString lengthStr = extractValue(barObj["CutLength"].toString());
            data.cutLength = lengthStr.toDouble();
        }

        // 6. 提取原料长度 (假设field6格式: "6,原料长度,XXX")
        if (barObj.contains("ProfileWhole") && barObj["ProfileWhole"].isString()) {
            QString materialStr = extractValue(barObj["ProfileWhole"].toString());
            data.materialLength = materialStr.toDouble();
        }

        // 7. 提取左角度 (假设field7格式: "7,左角度,XXX")
        if (barObj.contains("LeftAngle") && barObj["LeftAngle"].isString()) {
            QString leftAngleStr = extractValue(barObj["LeftAngle"].toString());
            data.leftAngle = leftAngleStr.toDouble();
        }

        // 8. 提取右角度 (假设field8格式: "8,右角度,XXX")
        if (barObj.contains("RightAngle") && barObj["RightAngle"].isString()) {
            QString rightAngleStr = extractValue(barObj["RightAngle"].toString());
            data.rightAngle = rightAngleStr.toDouble();
        }

        // 初始化切割数量为1
        data.cutCount = 1;

        data.workedCount = 0;

        // 创建唯一键用于统计相同组合（包含所有关键字段）
        QString uniqueKey = QString("%1|%2|%3|%4|%5|%6|%7|%8").arg(data.orderCode,
                                                                   data.profileType,
                                                                   data.productName,
                                                                   data.color,
                                                                   QString::number(data.cutLength),
                                                                   QString::number(data.materialLength),
                                                                   QString::number(data.leftAngle),
                                                                   QString::number(data.rightAngle));

        // 统计数量：若已存在相同组合则累加，否则添加新记录
        if (dataMap.contains(uniqueKey)) {
            dataMap[uniqueKey].cutCount++;
        } else {
            dataMap[uniqueKey] = data;
        }
    }

    aggregatedData = dataMap.values().toVector();

    // qDebug()<<"当前 Model DataList 总数: "<<model->count();

    // model->setDataList(aggregatedData);
    emit send_UpData_ListView_Signal(aggregatedData);

    // 数组式访问示例
    for (int i = 0; i < aggregatedData.size(); ++i) {
        const auto &data = aggregatedData[i];
        // model->addData(aggregatedData[i]);
        qDebug() << "记录" << i + 1 << " : "<<"订单号:"<<data.orderCode<<"类型:"<<data.profileType<<"名称: "<<data.productName<<"颜色: "<<data.color<<"切割长度: "<<data.cutLength<<"左角度: "<<data.leftAngle<<"右角度: "<<data.rightAngle<<"切割数量: "<<data.cutCount<<"原料长度: "<<data.materialLength;
    }

    qDebug()<<"新格尔 - 解析完成 : 共有 "<<aggregatedData.size()<<" 条数据";

    aggregatedData.clear();
}

void NetWorkManager::processCutData_SuZhi(const QJsonObject &originalData)
{
    QMap<QString, cutData> dataMap;  // 用于统计相同组合的数量

    QJsonObject dataObj = originalData["data"].toObject();


    const QJsonArray barArray = dataObj["bar"].toArray();
    for (const QJsonValue &barValue : barArray) {
        QJsonObject bar = barValue.toObject();
        QString barType = bar["barName"].toString();
        double barLength = bar["length"].toString().toDouble();
        QString barColor = bar["barColor"].toString();

        const QJsonArray pieceArray = bar["piece"].toArray();

        for (const QJsonValue &pieceValue : pieceArray) {
            QJsonObject piece = pieceValue.toObject();
            QJsonObject cutObj = piece["cut"].toObject();

            // 创建当前记录
            cutData current {
                piece["cc_code"].toString(),
                barType,
                piece["product_name"].toString(),
                barColor,
                piece["length"].toString().toDouble(),
                piece["count"].toInt(),
                barLength,
                cutObj["sxB"].toDouble(),
                cutObj["dxB"].toDouble(),
                0
            };


            // 创建唯一键用于统计相同组合（包含所有关键字段）
            QString uniqueKey = QString("%1|%2|%3|%4|%5|%6|%7|%8").arg(current.orderCode,
                                                                       current.profileType,
                                                                       current.productName,
                                                                       current.color,
                                                                       QString::number(current.cutLength),
                                                                       QString::number(current.materialLength),
                                                                       QString::number(current.leftAngle),
                                                                       QString::number(current.rightAngle));

            // 统计数量：若已存在相同组合则累加，否则添加新记录
            if (dataMap.contains(uniqueKey)) {
                dataMap[uniqueKey].cutCount++;
            } else {
                dataMap[uniqueKey] = current;
            }
        }
    }


    // 转换为数组式存储
    aggregatedData = dataMap.values().toVector();

    // qDebug()<<"当前 Model DataList 总数: "<<model->count();

    // model->setDataList(aggregatedData);
    emit send_UpData_ListView_Signal(aggregatedData);


    // 数组式访问示例
    for (int i = 0; i < aggregatedData.size(); ++i) {
        const auto &data = aggregatedData[i];
        // model->addData(aggregatedData[i]);
        qDebug() << "记录" << i + 1 << " : "<<"订单号:"<<data.orderCode<<"类型:"<<data.profileType<<"名称: "<<data.productName<<"颜色: "<<data.color<<"切割长度: "<<data.cutLength<<"左角度: "<<data.leftAngle<<"右角度: "<<data.rightAngle<<"切割数量: "<<data.cutCount<<"原料长度: "<<data.materialLength;
    }

    qDebug()<<"速制 - 解析完成 : 共有 "<<aggregatedData.size()<<" 条数据";

    aggregatedData.clear();
}

void NetWorkManager::processCudata_ChuangPin(const QJsonObject &originalData)
{
    QJsonArray dataArray = originalData["data"].toArray();
    QMap<QString, cutData> dataMap;  // 用于统计相同组合的切割数量

    // 遍历数据数组
    foreach (const QJsonValue& value, dataArray) {
        if (!value.isObject()) continue;
        QJsonObject item = value.toObject();

        cutData data;

        // 1. 提取订单编号 (orderCode)
        if (item.contains("orderCode") && item["orderCode"].isString()) {
            data.orderCode = item["orderCode"].toString().trimmed();
        }

        // 2. 提取型材类型 (barName + extra_Pie组合)
        QString barName = item["barName"].toString().trimmed();
        QString extraPie = item["extra_Pie"].toString().trimmed();
        if (!barName.isEmpty() && !extraPie.isEmpty()) {
            data.profileType = QString("%1（%2）").arg(barName).arg(extraPie);
        } else if (!barName.isEmpty()) {
            data.profileType = barName;
        }

        // 3. 提取产品名称 (product_name)
        if (item.contains("product_name") && item["product_name"].isString()) {
            data.productName = item["product_name"].toString().trimmed();
        }

        // 4. 提取颜色 (barColor)
        if (item.contains("barColor") && item["barColor"].isString()) {
            data.color = item["barColor"].toString().trimmed();
        }
        // 处理空颜色显示
        if (data.color.isEmpty()) {
            data.color = "/";
        }

        // 5. 提取切割长度 (length，直接获取数值类型)
        if (item.contains("length") && item["length"].isDouble()) {
            data.cutLength = item["length"].toDouble();
        }

        // 6. 提取原料长度 (barLength，转换为double)
        if (item.contains("barLength") && item["barLength"].isString()) {
            data.materialLength = item["barLength"].toString().toDouble();
        }

        // 7. 提取左侧角度 (sxB，直接获取数值类型)
        if (item.contains("sxB") && item["sxB"].isDouble()) {
            data.leftAngle = item["sxB"].toDouble();
        }

        // 8. 提取右侧角度 (dxB，直接获取数值类型)
        if (item.contains("dxB") && item["dxB"].isDouble()) {
            data.rightAngle = item["dxB"].toDouble();
        }

        data.workedCount = 0;

        // 创建唯一键用于统计相同规格组合
        // 创建唯一键用于统计相同组合（包含所有关键字段）
        QString uniqueKey = QString("%1|%2|%3|%4|%5|%6|%7|%8").arg(data.orderCode,
                                                                   data.profileType,
                                                                   data.productName,
                                                                   data.color,
                                                                   QString::number(data.cutLength),
                                                                   QString::number(data.materialLength),
                                                                   QString::number(data.leftAngle),
                                                                   QString::number(data.rightAngle));

        // 统计切割数量
        if (dataMap.contains(uniqueKey)) {
            dataMap[uniqueKey].cutCount++;
        } else {
            data.cutCount = 1;  // 初始化为1
            dataMap[uniqueKey] = data;
        }
    }

    // 转换为数组式存储
    aggregatedData = dataMap.values().toVector();

    // model->setDataList(aggregatedData);
    emit send_UpData_ListView_Signal(aggregatedData);

    // 数组式访问示例
    for (int i = 0; i < aggregatedData.size(); ++i) {
        const auto &data = aggregatedData[i];
        // // model->addData(aggregatedData[i]);
        qDebug() << "记录" << i + 1 << " : "<<"订单号:"<<data.orderCode<<"类型:"<<data.profileType<<"名称: "<<data.productName<<"颜色: "<<data.color<<"切割长度: "<<data.cutLength<<"左角度: "<<data.leftAngle<<"右角度: "<<data.rightAngle<<"切割数量: "<<data.cutCount<<"原料长度: "<<data.materialLength;
    }

    qDebug()<<"创品 - 解析完成 : 共有 "<<aggregatedData.size()<<" 条数据";

    aggregatedData.clear();
}

void NetWorkManager::recv_Scanner_Result_ChangFeng_Slots(const QByteArray &result)
{
    qDebug()<<"NetWork_Manager接收内容: "<<result;

    emit send_NetWork_ChangFeng_Url(QString(result));
}

void NetWorkManager::recv_Scanner_Result_XinGeEr_Slots(const QByteArray &result)
{
    qDebug()<<"NetWork_Manager接收内容: "<<result;

    emit send_NetWork_XinGeEr_Url(QString(result));
}

void NetWorkManager::recv_Scanner_Result_SuZhi_Slots(const QByteArray &result)
{
    qDebug()<<"NetWork_Manager接收内容: "<<result;

    emit send_NetWork_SuZhi_Url(QString(result));
}

void NetWorkManager::recv_Scanner_Result_ChuangPin_Slots(const QByteArray &result)
{
    qDebug()<<"NetWork_Manager接收内容: "<<result;

    emit send_NetWork_ChuangPin_Url(QString(result));
}

void NetWorkManager::recv_NetWork_ChangFeng_Process_List_Slots(QString URL)
{
    // TenantId 为客户唯一 接口
    QUrl requestUrl("http://cfwincad.cfsuper.com/api/project/opt_1D_InfoDetail?TenantId=19552266480965&ID=" + URL);

    // model->clear();

    qDebug()<<requestUrl;

    QNetworkRequest request(requestUrl);

    QNetworkReply* reply = m_NetWorkManager->get(request);

    QObject::connect(reply,&QNetworkReply::finished,this,[=](){
        if(reply->error() == QNetworkReply::NoError)
        {
            // QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

            QByteArray responseData = reply->readAll();

            // qDebug()<<"状态码:"<<statusCode.toInt();

            // qDebug()<<"响应数据:"<<responseData;

            QJsonParseError err;

            QJsonDocument document = QJsonDocument::fromJson(responseData,&err);

            if(err.error != QJsonParseError::NoError)
            {
                qDebug()<<"Json 格式错误";
                return ;
            }
            else
            {
                QJsonObject rootObject = document.object();

                QJsonValue statusValue = rootObject.value("code");
                qDebug()<<"状态:"<<statusValue.toInt();
                QJsonValue messageValue = rootObject.value("message");
                qDebug()<<"信息:"<<messageValue.toString();
                // QJsonObject dataObj = rootObject["data"].toObject();

                // 整合函数 - 速制
                processCudata_ChangFeng(rootObject);
            }
        }

    });
}

void NetWorkManager::recv_NetWork_XinGeEr_Process_List_Slots(QString URL)
{

    QUrl requestUrl("https://open.thinkerx.com/api/third/eqinterface.html?method=getorder&device_code=4ebdb3d6ac1411ed8d2d00163e18d113&order_code=" + URL);

    // model->clear();

    qDebug()<<requestUrl;

    QNetworkRequest request(requestUrl);

    QNetworkReply* reply = m_NetWorkManager->get(request);

    QObject::connect(reply,&QNetworkReply::finished,this,[=](){
        if(reply->error() == QNetworkReply::NoError)
        {
            // QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

            QByteArray responseData = reply->readAll();

            // qDebug()<<"状态码:"<<statusCode.toInt();

            // qDebug()<<"响应数据:"<<responseData;

            QJsonParseError err;

            QJsonDocument document = QJsonDocument::fromJson(responseData,&err);

            if(err.error != QJsonParseError::NoError)
            {
                qDebug()<<"Json 格式错误";
                return ;
            }
            else
            {
                QJsonObject rootObject = document.object();

                QJsonValue statusValue = rootObject.value("code");
                qDebug()<<"状态:"<<statusValue.toInt();
                QJsonValue messageValue = rootObject.value("message");
                qDebug()<<"信息:"<<messageValue.toString();
                // QJsonObject dataObj = rootObject["data"].toObject();

                // 整合函数 - 新格尔
                processCudata_XinGeEr(rootObject);
            }
        }

    });
}

void NetWorkManager::recv_NetWork_SuZhi_Process_List_Slots(QString URL)
{
    QUrl requestUrl("https://40erp.cn/hangwei/index.php/produce/loadSCMachineData/" + URL);

    // model->clear();

    qDebug()<<requestUrl;

    QNetworkRequest request(requestUrl);

    QNetworkReply* reply = m_NetWorkManager->get(request);

    QObject::connect(reply,&QNetworkReply::finished,this,[=](){
        if(reply->error() == QNetworkReply::NoError)
        {
            // QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

            QByteArray responseData = reply->readAll();

            // qDebug()<<"状态码:"<<statusCode.toInt();

            // qDebug()<<"响应数据:"<<responseData;

            QJsonParseError err;

            QJsonDocument document = QJsonDocument::fromJson(responseData,&err);

            if(err.error != QJsonParseError::NoError)
            {
                qDebug()<<"Json 格式错误";
                return ;
            }
            else
            {
                QJsonObject rootObject = document.object();

                QJsonValue statusValue = rootObject.value("code");
                qDebug()<<"状态:"<<statusValue.toInt();
                QJsonValue messageValue = rootObject.value("message");
                qDebug()<<"信息:"<<messageValue.toString();
                // QJsonObject dataObj = rootObject["data"].toObject();

                // 整合函数 - 速制
                processCutData_SuZhi(rootObject);
            }
        }

    });
}

void NetWorkManager::recv_NetWork_ChuangPin_Process_List_Slots(QString URL)
{
    QUrl requestUrl("https://ytchuangpin.cn/api/Ext/GetCut?cid=13&order=" + URL);

    // model->clear();

    qDebug()<<requestUrl;

    QNetworkRequest request(requestUrl);

    QNetworkReply* reply = m_NetWorkManager->get(request);

    QObject::connect(reply,&QNetworkReply::finished,[=](){
        if(reply->error() == QNetworkReply::NoError)
        {
            // QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

            QByteArray responseData = reply->readAll();

            // qDebug()<<"状态码:"<<statusCode.toInt();

            // qDebug()<<"响应数据:"<<responseData;

            QJsonParseError err;

            QJsonDocument document = QJsonDocument::fromJson(responseData,&err);

            if(err.error != QJsonParseError::NoError)
            {
                qDebug()<<"Json 格式错误";
                return ;
            }
            else
            {
                QJsonObject rootObject = document.object();

                QJsonValue statusValue = rootObject.value("code");
                qDebug()<<"状态:"<<statusValue.toInt();
                QJsonValue messageValue = rootObject.value("message");
                qDebug()<<"信息:"<<messageValue.toString();
                // QJsonObject dataObj = rootObject["data"].toObject();

                // 整合函数 - 创品
                processCudata_ChuangPin(rootObject);
            }
        }

    });
}

NetWorkManager::NetWorkManager(QObject *parent)
    : QObject{parent}
{
     m_NetWorkManager = new QNetworkAccessManager(this);


     QObject::connect(this,&NetWorkManager::send_NetWork_ChangFeng_Url,this,&NetWorkManager::recv_NetWork_ChangFeng_Process_List_Slots);
     QObject::connect(this,&NetWorkManager::send_NetWork_XinGeEr_Url,this,&NetWorkManager::recv_NetWork_XinGeEr_Process_List_Slots);
     QObject::connect(this,&NetWorkManager::send_NetWork_SuZhi_Url,this,&NetWorkManager::recv_NetWork_SuZhi_Process_List_Slots);
     QObject::connect(this,&NetWorkManager::send_NetWork_ChuangPin_Url,this,&NetWorkManager::recv_NetWork_ChuangPin_Process_List_Slots);

     model = Online_Process_List_Model::getInstance(this);

     QObject::connect(this,&NetWorkManager::send_UpData_ListView_Signal,model,&Online_Process_List_Model::setDataList);

}

NetWorkManager::~NetWorkManager()
{

}
